// async function getUser() {
//   return await fetch('./1.json')
// }

// async function m1() {
//   const user = await getUser()
//   // other works
//   return user
// }

// async function m2() {
//   const user = await m1()
//   // other works
//   return user
// }

// async function m3() {
//   const user = await m2()
//   // other works
//   return user
// }

// async function main() {
//   const user = await m3()
//   console.log(user)
// }

function getUser() {
  return fetch('./1.json')
}

function m1() {
  const user = getUser()
  // other works
  return user
}

function m2() {
  const user = m1()
  // other works
  return user
}

function m3() {
  const user = m2()
  // other works
  return user
}

function main() {
  const user = m3()
  console.log(user)
}

function run(func) {
  const oldFetch = window.fetch
  let cache = {
    status: 'pending',
    value: null
  }
  // 改动环境
  function newFetch(...args) {
    /*
    if (有缓存) {
      return 缓存数据
    }
    1. 发送真实请求
    2. 保存数据
    */
    if (cache.status === 'fulfilled') {
      return cache.value
    } else if (cache.status === 'rejected') {
      throw cache.value
    }
    const prom = oldFetch(...args).then(resp => resp.json()).then(res => {
      cache.status = 'fulfilled'
      cache.value = res
    }, err => {
      cache.status = 'rejected'
      cache.value = err
    })
    throw prom
  }
  window.fetch = newFetch
  // 执行入口函数
  try {
    func()
  } catch (error) {
    if (error instanceof Promise) {
      error.finally(() => {
        window.fetch = newFetch
        func()
        window.fetch = oldFetch
      })
    }
  }
}
run(main)